""" FileDialogDelegateQt.py: Delegate that pops up a file dialog when double clicked.

Sets the model data to the selected file name.
"""


import os.path
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QStyledItemDelegate, QFileDialog
from PySide6.QtWidgets import QStyle
from PySide6 import QtWidgets
__author__ = "Marcel Goldschen-Ohm <marcel.goldschen@gmail.com>"


class FileDialogDelegateQt(QStyledItemDelegate):
    """ Delegate that pops up a file dialog when double clicked.
    Sets the model data to the selected file name.
    """
    def __init__(self, parent=None):
        QStyledItemDelegate.__init__(self, parent)
    def setEditorData(self,editor, index):
        value = index.model().data(index)
        editor.setText(str(value))
    def setModelData(self,editor,model,index):
        value = editor.text()
        model.setData(index, value)
    def updateEditorGeometry(self,editor,option,index):
        editor.setGeometry(option.rect)
    def createEditor(self, parent, option, index):
        """ Instead of creating an editor, just popup a modal file dialog
        and set the model data to the selected file name, if any.
        """
        pathToFileName = ""
        pathToFileName, temp = QFileDialog.getOpenFileName(None, "Open")
        if pathToFileName!="":
            index.model().setData(index, pathToFileName, Qt.EditRole)
        # index.model().dataChanged.emit(index, index)  # Tell model to update cell display.
        editor =QtWidgets.QLineEdit(parent)
        return editor;
        # return None
    def paint(self,painter, option, index):
        #注意，此时index是logicIndex（model坐标），我们可以通过拖拽表头项交换列来测试
        #QStyle会根据option的属性进行绘制，我们也可以不使用QStyle的规则，完全自定义
        opt = option
        #去掉焦点 setFocusPolicy(Qt::NoFocus);
        # opt.state &= ~QStyle.State_HasFocus
        #参照源码实现了自己的initStyleOption
        # self.initMyStyleOption(opt, index)
        value = index.model().data(index)
        opt.text = value
        widget = opt.widget
        if widget:
            style = widget.style() 
        else:
            style= QApplication.style()
        style.drawControl(QStyle.CE_ItemViewItem, opt, painter, widget)
    def displayText(self, value, locale):
        """ Show file name without path.
        """
        pathToFileName = str(value)
        path, fileName = os.path.split(pathToFileName)
        return fileName
